#define _CRT_SECURE_NO_WARNINGS 1

#include "List.h"

List* Listapply(Listdatatype x)
{
	List* newnode = (List*)malloc(sizeof(List));
	if (newnode == NULL)
	{
		perror("malloc");
		exit(1);
	}
	newnode->data = x;
	newnode->next = newnode;
	newnode->last = newnode;

	return newnode;
}

void Listinit(List** pphead)
{
	assert(pphead);
	*pphead = Listapply(-1);
}

void Listprint(List* phead)
{
	assert(phead);
	List* pcur = phead->next;

	while (pcur != phead)
	{
		printf("%d->", pcur->data);
		pcur = pcur->next;
	}
	printf("\n");
}

void Listpushback(List* phead, Listdatatype x)
{
	assert(phead);
	List* newnode = Listapply(x);
	
	newnode->last = phead->last;
	newnode->next = phead;
	
	phead->last->next = newnode;
	phead->last = newnode;
}

void Listpushfront(List* phead, Listdatatype x)
{
	assert(phead);
	List* newnode = Listapply(x);

	newnode->next = phead->next;
	newnode->last = phead;

	phead->next->last = newnode;
	phead->next = newnode;
}

List* Listfind(List* phead, Listdatatype x)
{
	assert(phead);
	List* pcur = phead->next;

	while (pcur != phead)
	{
		if (pcur->data == x)
			return pcur;
		pcur = pcur->next;
	}
	return NULL;
}

void Listinsertback(List* pos, Listdatatype x)
{
	assert(pos);
	List* newnode = Listapply(x);

	newnode->next = pos->next;
	newnode->last = pos;

	pos->next->last = newnode;
	pos->next = newnode;
}

void Listinsertfront(List* pos, Listdatatype x)
{
	assert(pos);
	List* newnode = Listapply(x);

	newnode->next = pos;
	newnode->last = pos->last;

	pos->last->next = newnode;
	pos->last = newnode;
}

void Listpopback(List* phead)
{
	assert(phead && phead->next != phead);
	List* del = phead->last;

	del->last->next = phead;
	phead->last = del->last;
	free(del);
	del = NULL;
}

void Listpopfront(List* phead)
{
	assert(phead && phead->next != phead);
	List* del = phead->next;

	del->next->last = phead;
	phead->next = del->next;
	free(del);
	del = NULL;
}

void Listdel(List* pos)
{
	assert(pos);

	pos->next->last = pos->last;
	pos->last->next = pos->next;
	free(pos);
	pos = NULL;
}

void Listchange(List* pos, Listdatatype x)
{
	assert(pos);
	pos->data = x;
}

void Listdestory(List* phead)
{
	assert(phead);
	List* pcur = phead->next;
	List* next = pcur;

	while (pcur != phead)
	{
		next = pcur->next;
		free(pcur);
		pcur = next;
	}
	free(phead);
	phead = NULL;
	pcur = next = NULL;
}
